package com.xiaoxin.codesandbox.utils;

import cn.hutool.core.date.StopWatch;
import com.xiaoxin.codesandbox.modle.ExecuteMessage;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 程序工具类
 */
public class ProcessUtil {
    /**
     * 运行并得到结果
     * @param compileProcess
     * @param optName
     * @return
     */
    public ExecuteMessage RunProcessAndGetResult(Process compileProcess,String optName){
        try {
            StopWatch stopWatch=new StopWatch();
            stopWatch.start();
            int value = compileProcess.waitFor();
            //判断是否编译成功，并打印信息
            ExecuteMessage executeMessage = new ExecuteMessage();
            if(value==0){
                System.out.println(optName+"成功");
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
                StringBuilder compileBuilder=new StringBuilder();
                String successLine="";
                while((successLine=bufferedReader.readLine())!=null){
                    compileBuilder.append(successLine);
                }
                executeMessage.setValue(value);
                executeMessage.setMessage(compileBuilder.toString());
            }else {
                System.out.println(optName+"失败");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
                StringBuilder compileBuilder = new StringBuilder();
                String errorLine = "";
                while ((errorLine = bufferedReader.readLine()) != null) {
                    compileBuilder.append(errorLine);
                }
                BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream()));
                StringBuilder errorCompileBuilder = new StringBuilder();
                while ((errorLine = errorBufferedReader.readLine()) != null) {
                    errorCompileBuilder.append(errorLine);
                }
                executeMessage.setValue(value);
                executeMessage.setMessage(compileBuilder.toString());
                executeMessage.setErrorMessage(errorCompileBuilder.toString());
            }
            stopWatch.stop();
            long costTime = stopWatch.getLastTaskTimeMillis();
            executeMessage.setCostTime(costTime);
            return executeMessage;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
